<?php
/*
 * Разлогинить - User::unProcessUser();
 */
class User
{

    private $user_id;
    private $name; // user_login
    private $pass; // user_pass
    private $role; // user_role
    private $space;
    private $user_logdate;

    private static $instance = null;


    function __construct($user = '', $pass = '', $options = array())
    {

        $this->space = SESSION_SPACE;

        if ($user == '')
            $this->name = 'guest';
        else
            $this->name = $user;

        $this->pass = $pass;

        #
        if(isset($options['user_id'])) $this->user_id = $options['user_id'];
        if(isset($options['user_role'])) $this->role = $options['user_role'];
        if(isset($options['user_login'])) $this->name = $options['user_login'];
        if(isset($options['user_pass'])) $this->pass = $options['user_pass'];
        if(isset($options['user_logdate'])) $this->user_logdate = $options['user_logdate'];

        self::$instance = $this;


    } // --

    public static function getInstance()
    {
        if (!isset(self::$instance)) {
            $className = __CLASS__;
            self::$instance = new $className;
        }

        return self::$instance;
    }

    /*
     * Закинуть юзера в сессию
     */
    function processUser()
    {

        // выставить оставшиеся поля
        // email = '';
        //var_dump($this);die;
        $space = $this->space;

        $info = $this->getUserInfo();

        if (true) {
            $r = Registry::getInstance();
            //$r->set('User', self::getInstance());

            $session = $r->session->get();

            //$session['backendUser'] = $info;
            $_SESSION[$space]['backendUser'] = $info;

            //$_SESSION['user'] = self::getInstance();
            //$_SESSION['user']['id'] = 1;
            /// asdr($_SESSION, '$_SESSION');die;
        }

    } // --

    function getUserInfo()
    {
        //TODO
        // взять инфу из БД
        $info = new stdClass();

        $info->name = $this->name;
        $info->pass = md5($this->pass); // Дополнительно шифруем перед тем, как положить в сессию
        $info->role = $this->role; ///'admin'; // [!] test
        $info->user_id = $this->user_id;

        return $info;
    }

    static function isUserExists($login, $pass)
    {

        $result = null;

        /*
        if ($login == 'admin' AND $pass == 'admin')
            return true;
        */
        $UserModel = new UserModel();
        $result = $UserModel->getUser($login, self::encode($pass));

        if(isset($result[0])){
            $tmp = array();
            if(isset($result[0]['user_id'])) $tmp['user_id'] = $result[0]['user_id'];
            if(isset($result[0]['user_role'])) $tmp['user_role'] = $result[0]['user_role'];
            if(isset($result[0]['user_login'])) $tmp['user_login'] = $result[0]['user_login'];
            //if(isset($result[0]['user_pass'])) $tmp['user_pass'] = $result[0]['user_pass'];
            unset($result);

            $result = $tmp;
        }

        return $result;
    }

    static function _sUserLogged()
    {
        ///TEST

        if (isset($_SESSION['user']))
            if ($_SESSION['user']) {
                //return 1;    //fb('admin');
                //    var_dump($_SESSION['user']);
            }

        // fb( __METHOD__.'-1');
        $r = Registry::getInstance();
        if ($r->has('User')) {
            $user = $r->get('User');
            if (is_object($user))
                if ((string)$user->name != 'guest')

                    return true;
        }


        return false;
    }

    static function isUserLogged()
    {
        // TODO user_id check

        $r = Registry::getInstance(); //fb($r->get('session'));
        if (!$r->has('session'))
            return false;
        if (!isset($r->get('session')->data['user']))
            return false;
        if (!is_object($r->get('session')->data['user']))
            return false;

        if (!isset($r->get('session')->data['user']->name))
            return false;
        if (!isset($r->get('session')->data['user']->role))
            return false;
        if (!isset($r->get('session')->data['user']->pass))
            return false;

        if (trim($r->get('session')->data['user']->name) === '')
            return false;
        if (trim($r->get('session')->data['user']->role) === '')
            return false;
        if (trim($r->get('session')->data['user']->pass) === '')
            return false;

        if (trim($r->get('session')->data['user']->name) === null)
            return false;
        if (trim($r->get('session')->data['user']->role) === null)
            return false;
        if (trim($r->get('session')->data['user']->pass) === null)
            return false;

        if (trim($r->get('session')->data['user']->name) === false)
            return false;
        if (trim($r->get('session')->data['user']->role) === false)
            return false;
        if (trim($r->get('session')->data['user']->pass) === false)
            return false;

        return true;
    }

    /*
     * раздлгинить пользователя
     */
    static function unProcessUser()
    {

        // удалить из реестра
        $r = Registry::getInstance();
        if ($r->has('User'))
            $r->set('User', null);

        // TODO очистить таблицу временного хранения юзеров

        $space = SESSION_SPACE;

        if(isset($_SESSION[$space]['backendUser']))
            unset($_SESSION[$space]['backendUser']);

        return true;
    }

    static function current()
    {
        $r = Registry::getInstance();
        $space = SESSION_SPACE;
        $my_space = $r->session->$space;

        $key = 'frontendUser';

        if($r->has('zone')){
            if($r->zone == 'backend'){
                $key = 'backendUser';
            }
        }

        if(isset($my_space[$key])){
            return $my_space[$key];
        }

        return false;

    }

    /*
     * Проверят, залогинен ли пользователь и админ ли он
     */
    static function isAdmin()
    {

        ///fb(Registry::getInstance()->session);die;
        //   fb(Registry::getInstance()->get('session'));die;
        $space = SESSION_SPACE;

        $r = Registry::getInstance();

        $result = false;

        if ($r->has('session')) {
            if ($r->session->has($space)) {
                $my_space = $r->session->$space;

                if (isset($my_space['backendUser'])) {
                    $backendUser = $my_space['backendUser'];

                    if(is_array($backendUser)){
                        if (isset($backendUser['role'])) {
                            if ($backendUser['role'] == 'admin') {
                                $result = true;
                            }
                        }
                    } elseif (is_object($backendUser)){
                        if (isset($backendUser->role)) {
                            if ($backendUser->role == 'admin') {
                                $result = true;
                            }
                        }
                    }

                }
            }
        }


        /*
        if($r->has('session'))
        if(isset($r->get('session')->data['user']))
        if(is_object($r->get('session')->data['user']))
        if($r->get('session')->data['user']->role == 'admin')
          return true;
        */

        return $result;
    }

    static function encode($word)
    {
        return md5(md5($word . "^=+_0") . ":" . substr(md5($word),0,4) );
    }


} // -- end of class

?>